import React from 'react'
import { Dropdown, message, Button, Modal, Form, Input, TreeSelect } from 'antd'
import { EllipsisOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import style from './DepartmentEmployee.module.less'
import Employee from './Employee'
const { confirm } = Modal

class DepartmentEmployee extends Component {
  state = {
    roleList: [],
    roleMap: {},
    departmentTree: [],
    departmentTreeData: [],
    currentDepartment: null,
    addDepartmentModalVisible: false,
    modifyDepartmentModalVisible: false,
    modifyDepartment: {}
  }

  addDepartmentFormRef = React.createRef()
  modifyDepartmentFormRef = React.createRef()

  // 修改部门按钮回调
  modifyDepartmentButtonHandle (data) {
    this.setState({
      modifyDepartment: data,
      modifyDepartmentModalVisible: true
    }, () => {
      this.modifyDepartmentFormRef.current.resetFields()
    })
  }

  // 格式化对象为数组
  formatListFromObject (obj) {
    const keys = Object.keys(obj)
    return keys.map(key => obj[key])
  }

  // 将children map对象转化为list
  formatTreeChildrenMapToList (obj) {
    const list = this.formatListFromObject(obj)
    list.forEach(li => {
      if (li.children) {
        li.children = this.formatTreeChildrenMapToList(li.children)
      }
    })
    return list
  }

  // 格式化树选择器所需要的数据格式
  formatTreeData (list) {
    return list.map(li => {
      return {
        title: li.name,
        value: String(li.id),
        children: li.children ? this.formatTreeData(li.children) : null
      }
    })
  }

  // 获取部门树
  getDepartmentTree () {
    return this.$get('/api/xapc/department_tree')
      .then(res => {
        if (res.status === 1) {
          const departmentTree = this.formatTreeChildrenMapToList(res.data)
          const departmentTreeData = this.formatTreeData(departmentTree)
          const state = {
            departmentTree,
            departmentTreeData
          }
          if (!this.state.currentDepartment && departmentTree[0]) {
            state.currentDepartment = departmentTree[0]
          }
          this.setState(state)
        } else {
          message.warning(res.message)
        }
      })
  }

  // 获取角色列表
  getRoleList () {
    return this.$get('/api/admin/role', {
      appid: '111',
      page_size: 100,
      current: 1
    }).then(res => {
      if (res.status === 1) {
        const list = this.formatListFromObject(res.data.list) || []
        this.setState({
          roleMap: res.data.list,
          roleList: list
        })
      } else {
        message.warning(res.message)
      }
    })
  }

  // 获取初始化数据
  getInitData () {
    const hide = message.loading('加载中', 120)
    Promise.all([this.getRoleList(), this.getDepartmentTree()])
      .then(res => hide())
      .catch(res => hide())
  }

  // 改变当前选中的部门
  changeCurrentDepartment (obj) {
    this.setState({
      currentDepartment: obj
    })
  }

  // 点击新增部门按钮回调
  addDepartmentHandle () {
    this.addDepartmentFormRef.current.resetFields()
    this.setState({
      addDepartmentModalVisible: true
    })
  }

  // 确定新增部门按钮回调
  decideAddDepartment () {
    this.addDepartmentFormRef.current.submit()
  }

  // 取消新增部门按钮回调
  cancelAddDepartment () {
    this.addDepartmentFormRef.current.resetFields()
    this.setState({
      addDepartmentModalVisible: false
    })
  }

  // 新增部门请求
  addDepartmentRequest (data) {
    const hide = message.loading('添加部门中', 120)
    data.pid = String(data.pid)
    this.$post('/api/xapc/department', data)
      .then(res => {
        hide()
        if (res.status === 1) {
          this.getDepartmentTree()
          this.setState({
            addDepartmentModalVisible: false
          })
        } else {
          message.warning(res.message)
        }
      }).catch(() => hide())
  }

  // 确定修改部门按钮回调
  decideModifyDepartment () {
    this.modifyDepartmentFormRef.current.submit()
  }

  // 取消修改部门按钮回调
  cancelModifyDepartment () {
    this.modifyDepartmentFormRef.current.resetFields()
    this.setState({
      modifyDepartmentModalVisible: false
    })
  }

  // 修改部门请求
  modifyDepartmentRequest (data) {
    const hide = message.loading('修改部门中', 120)
    const id = data.id
    data.pid = String(data.pid)
    delete data.id
    this.$put(`/api/xapc/department/${id}`, data)
      .then(res => {
        hide()
        if (res.status === 1) {
          this.getDepartmentTree()
          this.setState({
            modifyDepartmentModalVisible: false
          })
        } else {
          message.warning(res.message)
        }
      }).catch(() => hide())
  }

  // 删除部门按钮回调
  delDepartmentHandle (obj) {
    confirm({
      title: '提示',
      icon: <ExclamationCircleOutlined />,
      content: `您确定要删除 ${obj.name} 吗？`,
      onOk: () => {
        this.delDepartmentRequest(obj.id)
      }
    })
  }

  // 删除部门请求
  delDepartmentRequest (id) {
    const hide = message.loading('删除部门中', 120)
    this.$delete(`/api/xapc/department/${id}`).then(res => {
      hide()
      if (res.status === 1) {
        if (this.state.currentDepartment.id === id) {
          this.setState({
            currentDepartment: null
          }, () => {
            this.getDepartmentTree()
          })
        }
      } else {
        message.warning(res.message)
      }
    }).catch(() => hide())
  }

  componentDidMount () {
    this.getInitData()
  }

  // 生成部门操作菜单
  renderMenu (data) {
    return {
      items: [
        { label: '修改', key: '1', onClick: () => { this.modifyDepartmentButtonHandle(data) } },
        { label: '删除', key: '2', danger: true, onClick: () => { this.delDepartmentHandle(data) } }
      ]
    }
  }

  // 渲染部门树
  renderDepartmentTree (list, operatable = true) {
    return (
      <ul className={style['department-list']}>
        {
          list.map(li => this.renderDepartmentLeaf(li, operatable))
        }
      </ul>
    )
  }

  // 渲染部门树叶子节点
  renderDepartmentLeaf (li, operatable = true) {
    let className = ''
    let { currentDepartment: c } = this.state
    if (!c) {
      c = {}
    }
    if (li.id === c.id) {
      className = style.active
    }
    return (
      <li key={li.id} className={className}>
        <div className={style['department-li']}>
          <div onClick={() => this.changeCurrentDepartment(li)}>{li.name}</div>
          {operatable ? (
            <Dropdown menu={this.renderMenu(li)} trigger={['click']} onClick={e => e.stopPropagation()}>
              <i>
                <EllipsisOutlined />
              </i>
            </Dropdown>
          ) : null}
        </div>
        {li.children ? this.renderDepartmentTree(li.children) : null}
      </li>
    )
  }

  // 渲染新增部门弹框
  renderAddDepartmentModal () {
    return (
      <Modal
        title='添加部门'
        forceRender
        open={this.state.addDepartmentModalVisible}
        maskClosable={false}
        onOk={() => this.decideAddDepartment()}
        onCancel={() => this.cancelAddDepartment()}
      >
        <Form name='add_department' ref={this.addDepartmentFormRef} onFinish={v => this.addDepartmentRequest(v)}>
          <Form.Item name='name' label='部门名称' rules={[{ required: true, message: '部门名称不能为空' }]}>
            <Input placeholder='请输入部门名称' />
          </Form.Item>
          <Form.Item name='pid' label='上级部门' rules={[{ required: true, message: '上级部门不能为空' }]}>
            <TreeSelect
              style={{ width: '100%' }}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              treeData={this.state.departmentTreeData}
              placeholder='请选择上级部门'
              treeDefaultExpandAll
            />
          </Form.Item>
        </Form>
      </Modal>
    )
  }

  // 渲染修改部门弹框
  renderModifyDepartmentModal () {
    return (
      <Modal
        title='修改部门'
        forceRender
        open={this.state.modifyDepartmentModalVisible}
        maskClosable={false}
        onOk={() => this.decideModifyDepartment()}
        onCancel={() => this.cancelModifyDepartment()}
      >
        <Form name='modify_department' ref={this.modifyDepartmentFormRef} onFinish={v => this.modifyDepartmentRequest(v)} initialValues={this.state.modifyDepartment}>
          <Form.Item name='id' noStyle><span /></Form.Item>
          <Form.Item name='status' noStyle><span /></Form.Item>
          <Form.Item name='name' label='部门名称' rules={[{ required: true, message: '部门名称不能为空' }]}>
            <Input placeholder='请输入部门名称' />
          </Form.Item>
          <Form.Item name='pid' label='上级部门' rules={[{ required: true, message: '上级部门不能为空' }]}>
            <TreeSelect
              style={{ width: '100%' }}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              treeData={this.state.departmentTreeData}
              placeholder='请选择上级部门'
              treeDefaultExpandAll
            />
          </Form.Item>
        </Form>
      </Modal>
    )
  }

  render () {
    const { currentDepartment, roleList, roleMap, departmentTreeData } = this.state
    return (
      <div className={style.container}>
        {this.renderAddDepartmentModal()}
        {this.renderModifyDepartmentModal()}
        <div className={style['left-container']}>
          {this.renderDepartmentTree(this.state.departmentTree, false)}
          <Button type='link' block onClick={() => this.addDepartmentHandle()}>+添加部门</Button>
        </div>
        <div className={style['right-container']}>
          <Employee currentDepartment={currentDepartment} roleList={roleList} roleMap={roleMap} departmentTreeData={departmentTreeData} />
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {

  }
})

export default connect(mapState, mapDispatch)(DepartmentEmployee)
